/**
 * Write a test program that illustrates your system’s behavior when a process is blocked
 * while trying to write lock a range of a file and additional read-lock requests are made. Is
 * the process requesting a write lock starved by the processes read locking the file?
 **/

#include "apue.h"

#include <fcntl.h>

int main()
{
  int fd;
  pid_t pid;
  // 创建文件
  if ((fd = open("temp", O_RDWR | O_CREAT, 0666)) < 0) {
    err_sys("open error");
  }
  if (write(fd, "ab", 2) != 2) {
    err_sys("write error");
  }
  printf("fd=%d\n", fd);
  // 加读锁
  if (read_lock(fd, 0, SEEK_SET, 1) < 0) {
    err_sys("readlock error");
  } else {
    printf("parent  : get readlock\n");
  }

  // 创建进程加读锁
  pid = fork();
  if (pid < 0) {
    err_sys("fork error");
  } else if (pid > 0) {
    // 父进程
    sleep(2);
    // 继续创建进程加读锁
    pid = fork();
    if (pid > 0) {
      if (read_lock(fd, 0, SEEK_SET, 1) < 0) {
        err_sys("readlock error1");
      } else {
        printf("p_parent: get readlock.\n");
      }
    } else {
      if (read_lock(fd, 0, SEEK_SET, 1) < 0) {
        err_sys("readlock error2");
      } else {
        printf("p_child : get readlock.\n");
      }
    }
    sleep(3);
    un_lock(fd, 0, SEEK_SET, 1);
  } else {
    // 子进程
    sleep(1);
    // 尝试加写锁
    printf("child   : try to get writelock.\n");
    if (writew_lock(fd, 0, SEEK_SET, 1) < 0) {
      err_sys("writelock error");
    }
    printf("child   : get writelock\n");
    un_lock(fd, 0, SEEK_SET, 1);
  }
  return 0;
}